package com.cx.gateway.config;


import cn.hutool.core.convert.Convert;
import com.alibaba.fastjson.JSON;
import com.cx.gateway.menu.MenuService;
import com.cx.gateway.redis.RedisConstant;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhangcx
 * @Description TODO
 * @date 2022/6/8 16:41
 * @email zhangcx@bluemoon.com.cn
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class AuthorizationManagerConfig implements ReactiveAuthorizationManager<AuthorizationContext> {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private MenuService menuService;

    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> mono, AuthorizationContext authorizationContext) {
        Object object = redisTemplate.opsForHash().entries(RedisConstant.MENU_INFO.getKey());
        log.info("123：{}", JSON.toJSONString(object));
        URI uri = authorizationContext.getExchange().getRequest().getURI();
        List<String> authorities = menuService.getMenuList(uri.getPath());
        authorities = authorities.stream().map(i -> i = ResourceServerConfig.AUTHORITY_PREFIX + i).collect(Collectors.toList());
        Flux<String> authority = mono.filter(Authentication::isAuthenticated)
                .flatMapIterable(Authentication::getAuthorities)
                .map(GrantedAuthority::getAuthority);
        return authority.doOnNext(q -> {
                    log.info("authority:{}", q);
                })
                .any(authorities::contains)
                .map(AuthorizationDecision::new)
                .defaultIfEmpty(new AuthorizationDecision(false));
    }

    @Override
    public Mono<Void> verify(Mono<Authentication> authentication, AuthorizationContext object) {
        return null;
    }
}
